﻿using H.Nets;
using H.Utils;
using System;
using System.Collections.Generic;
using System.Net;
using System.Windows.Forms;

namespace LogServer
{
    public partial class MainLogForm : Form
    {
        /// <summary>
        /// 服务器组件
        /// </summary>
        private readonly ITcpServer Server;

        /// <summary>
        /// identifer和TabPage的映射
        /// </summary>
        private readonly Dictionary<string, TabPage> TabPageMapping = new Dictionary<string, TabPage>();

        public MainLogForm()
        {
            InitializeComponent();
        }

        public MainLogForm(ITcpServer server) : this()
        {
            Server = server;
            Server.NewConnection += Server_NewConnection;
            Server.Start();
        }

        private void MainLogForm_Load(object sender, EventArgs e)
        {
            TB_IP.Text = GetLocalIp();
        }

        private void Server_NewConnection(ITcpClient newClient)
        {
            void statusChange(bool status)
            {
                Invoke(new Action(() =>
                {
                    if (!TabPageMapping.TryGetValue(newClient.Identifier, out TabPage page))
                    {
                        page = CreateNewTab(newClient.Identifier);
                    }
                    page.Text = $"{newClient.Identifier}({(status ? "在线" : "离线")})";
                    if (status)
                    {
                        TC_Main.SelectedTab = page;
                    }
                }));
            };

            statusChange(true);
            newClient.StatusChange += statusChange;
            newClient.Rename += NewClient_OnClientRename;
            newClient.Recieved += (int topicID, int typeID, int dataLength, byte[] buffer) =>
            {
                if (typeID == HFrameType.LOG && TabPageMapping.TryGetValue(newClient.Identifier, out TabPage page))
                {
                    Invoke(new Action(() =>
                    {
                        if (page.Tag is TextBox textBox)
                        {
                            textBox.AppendText(buffer.GetUTF8String(dataLength));
                        }
                    }));
                }
            };
        }

        private void NewClient_OnClientRename(string oldName, string newName)
        {
            Invoke(new Action(() =>
            {
                if (TabPageMapping.TryGetValue(oldName, out TabPage oldPage))
                {
                    if (TabPageMapping.TryGetValue(newName, out TabPage newPage))
                    {
                        //进行合并
                        TextBox newTextBox = newPage.Controls["TB_Main"] as TextBox;
                        newTextBox.AppendText(oldPage.Controls["TB_Main"].Text);
                    }
                    else
                    {
                        //进行改名
                        oldPage.Text = newName;
                        TabPageMapping.Add(oldName, oldPage);
                    }
                    TabPageMapping.Remove(oldName);
                }
            }));
        }


        /// <summary>
        /// 创建一个新的TabPage
        /// </summary>
        private TabPage CreateNewTab(string identify)
        {
            TextBox textBox = new TextBox()
            {
                Name = "TB_Main",
                Multiline = true,
                Dock = DockStyle.Fill,
                BorderStyle = BorderStyle.None,
                WordWrap = false,
                ScrollBars = ScrollBars.Both
            };
            TabPage page = new TabPage()
            {
                Text = identify,
                Tag = textBox,
                AutoScroll = true,
            };

            page.Controls.Add(textBox);

            TC_Main.TabPages.Add(page);
            TabPageMapping.Add(identify, page);

            return page;
        }

        public string GetLocalIp()
        {
            ///获取本地的IP地址
            string AddressIP = string.Empty;
            foreach (IPAddress _IPAddress in Dns.GetHostEntry(Dns.GetHostName()).AddressList)
            {
                if (_IPAddress.AddressFamily.ToString() == "InterNetwork")
                {
                    AddressIP = _IPAddress.ToString();
                }
            }
            return AddressIP;
        }

    }
}
